package com.jack.online.study.service.vod.impl;


import com.jack.online.study.common.base.result.ResultCodeEnum;
import com.jack.online.study.common.exception.GuliException;
import com.jack.online.study.mapper.vod.MediaMapper;
import com.jack.online.study.model.vod.dao.Media;
import com.jack.online.study.service.vod.MediaService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.MimeType;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

@Service
@Slf4j
public class MediaServiceImpl implements MediaService {

    @Resource
    private MediaMapper mediaMapper;


    @Override
    public String uploadVideo(MultipartFile file, String originalFilename) {
        long id = System.currentTimeMillis();
        String videoId = Long.toString(id);
        try {
            Media media = new Media();
            media.setId(id);
            media.setVideoName(file.getOriginalFilename());
            media.setBlobData(file.getBytes());
            int a = mediaMapper.insertMedia(media);
            return videoId;
        } catch (IOException e) {
            log.error("视频上传失败", e);
            throw new GuliException(ResultCodeEnum.VIDEO_UPLOAD_ALIYUN_ERROR);
        }
    }

    @Override
    public void removeVideo(String videoId) {
        int a = mediaMapper.deleteById(Long.parseLong(videoId));
    }

    @Override
    public void removeVideoByIdList(List<String> videoIdList) {
        videoIdList.forEach(e -> {
            mediaMapper.deleteById(Long.parseLong(e));
        });
    }

    @Override
    public String getPlayAuth(String videoSourceId) {

        return "";
    }

    @Override
    public ResponseEntity<Object> playVideo(Long videoId) {
        try {
            MediaType mediaType = MediaType.parseMediaType("video/mp4");
            Media video = mediaMapper.selectVideo(videoId);
            return ResponseEntity.ok()
                    .contentType(mediaType)
                    .body(video.getBlobData());
        } catch (Exception e) {
            log.error("播放视频出错");
            return ResponseEntity.ofNullable(null);
        }
    }

    /**
     * 删除视频
     * @param client 发送请求客户端
     * @return DeleteVideoResponse 删除视频响应数据
     * @throws Exception
     */
    /*public static DeleteVideoResponse deleteVideo(DefaultAcsClient client) throws Exception {
        DeleteVideoRequest request = new DeleteVideoRequest();
        //支持传入多个视频ID，多个用逗号分隔
        request.setVideoIds("VideoId1,VideoId2");
        return client.getAcsResponse(request);
    }*/
}
